#!/usr/bin/python

import cv2
import cv2.cv as cv
import math

class Processor:    
    def __init__(self):
        self.__rectangles = 0
        self.__cannyThres = 100
        self.__houghthres = 40
        self._blue = (255,0,0)
        self._red = (0,0,255)
    
    def process(self, img):
        gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
        self.img = cv2.cvtColor(gray, cv2.COLOR_GRAY2RGB)
        canny = cv2.Canny(gray, 80, 120)    
        kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(2,2))
        edges = cv2.dilate(canny,kernel)
        

        cv2.imshow("D", edges)
        cv.MoveWindow("D", 800,0)
        cv2.createTrackbar("Thres","A",self.__houghthres, 200, self.setThres)
        
        lines = cv2.HoughLinesP(canny, 1, 1*math.pi/180, self.__houghthres, None, 40, 15)
        self.drawLines(lines)

    def drawLines(self, lines):
        string = "%d" % lines.size
        cv2.putText(self.img, string, (20,20), cv2.FONT_HERSHEY_PLAIN,1.0,self._red)
        for line in lines[0]:
            pt1 = (line[0],line[1])
            pt2 = (line[2],line[3])
            if( self.dist(pt1,pt2) > 10 ):
                cv2.line(self.img, pt1, pt2, self._red, 2)

    def dist(self,p1, p2):
        return math.sqrt(math.pow(p2[0] - p1[0],2) + math.pow(p2[1] - p1[1],2) );

    def setThres(self, a):
        self.__houghthres = a
